<template>
  <s-clean-layout :title="isEdit ? '修改人情' : '添加人情'" navbar="normal">
    <view class="accounting-edit-container">
      <!-- 表单内容 -->
      <scroll-view scroll-y class="form-container">
        <!-- 收支切换 -->
        <view class="tabs">
          <view
            class="tab-item"
            :class="{ active: accountType === '收入' }"
            @tap="accountType = '收入'"
          >
            收入
          </view>
          <view
            class="tab-item"
            :class="{ active: accountType === '支出' }"
            @tap="accountType = '支出'"
          >
            支出
          </view>
        </view>

        <!-- 金额输入 -->
        <view class="amount-input">
          <input
            type="digit"
            v-model="amount"
            placeholder="请输入金额"
            class="amount-field"
          />
          <view class="camera-icon" @tap="scanInvoice">
            <uni-icons type="camera" size="24" color="#333"></uni-icons>
          </view>
        </view>

        <!-- 添加图片展示区域 -->
        <view class="image-list" v-if="formData.images.length > 0">
          <view v-for="(image, index) in formData.images" :key="index" class="image-item">
            <image :src="image" mode="aspectFill" @tap="previewImage(index)"></image>
            <view class="delete-btn" @tap.stop="deleteImage(index)">
              <text class="delete-icon">×</text>
            </view>
          </view>
        </view>

        <!-- 类型选择 -->
        <view class="form-item" @tap="navigateToTypeSelector">
          <text class="item-label">类型</text>
          <view class="item-value">
            <text class="type-value">{{ type || '请选择' }}</text>
            <uni-icons type="right" size="16" color="#CCCCCC"></uni-icons>
          </view>
        </view>
        
        <!-- 事件名称 -->
        <view class="form-item">
          <text class="item-label">事件名称</text>
          <view class="item-value">
            <input
              v-model="eventName"
              placeholder="请输入事件名称"
              class="input-field"
            />
          </view>
        </view>
        
        <!-- 礼品 -->
        <view class="form-item">
          <text class="item-label">礼品</text>
          <view class="item-value">
            <input
              v-model="giftItem"
              placeholder="请输入礼品"
              class="input-field"
            />
          </view>
        </view>

        <!-- 账户选择 -->
        <view class="form-item" @tap="showAccountSelector">
          <text class="item-label">账户</text>
          <view class="item-value">
            <text class="account-value">{{ account || '请选择' }}</text>
            <uni-icons type="right" size="16" color="#CCCCCC"></uni-icons>
          </view>
        </view>

        <!-- 交易日期 -->
        <view class="form-item" @tap="showDatePicker">
          <text class="item-label">交易日期</text>
          <view class="item-value">
            <text class="date-value">{{ date }}</text>
            <uni-icons type="right" size="16" color="#CCCCCC"></uni-icons>
          </view>
        </view>

        <!-- 备注 -->
        <view class="form-item remark-item">
          <textarea
            v-model="remark"
            placeholder="备注"
            class="remark-textarea"
            maxlength="200"
          />
        </view>
        
        <!-- 底部间距，确保内容不被底部保存按钮遮挡 -->
        <view style="height: 120rpx;"></view>
      </scroll-view>
      
      <!-- 底部保存按钮 -->
      <view class="bottom-save-button" @tap="saveAccounting">
        <text>保存</text>
      </view>

      <!-- 类型选择器 -->
      <s-dropdown-selector
        v-model:visible="typeSelectorVisible"
        v-model="type"
        :title="'类型'"
        :options="typeOptions"
        @confirm="onTypeSelected"
      />

      <!-- 账户选择器 -->
      <s-dropdown-selector
        v-model:visible="accountSelectorVisible"
        v-model="account"
        :title="'账户'"
        :options="accountOptions"
        @confirm="onAccountSelected"
      />

      <!-- 日期选择器 -->
      <s-datetime-picker
        v-model:visible="datePickerVisible"
        :title="'选择日期'"
        :initialDate="date || new Date()"
        mode="date"
        @confirm="onDateSelected"
      />
    </view>
  </s-clean-layout>
</template>

<script setup>
import { ref, computed, onMounted, watch, reactive } from 'vue';
import TransactionApi from '@/sheep/api/money/transaction';
import FileApi from '@/sheep/api/infra/file';

// 编辑模式标志
const isEdit = ref(false);

// 表单数据
const accountType = ref('收入');
const amount = ref('');
const type = ref('');
const typeId = ref(null); // 添加类型ID字段
const account = ref('微信');
const date = ref('');
const remark = ref('');
const eventName = ref(''); // 添加事件名称字段
const giftItem = ref(''); // 添加礼品字段

// 选择器可见性
const typeSelectorVisible = ref(false);
const accountSelectorVisible = ref(false);
const datePickerVisible = ref(false);

// 类型选项
const typeOptions = computed(() => {
  return accountType.value === '收入' ? 
    ['礼金', '红包', '借入', '工资', '其他'] : 
    ['礼金', '红包', '借出', '消费', '其他'];
});

// 账户选项
const accountOptions = ref(['微信', '支付宝', '现金', '银行卡', '其他']);

// 账户类型映射
const accountTypeMap = {
  '微信': 'WCHAT',
  '支付宝': 'ALIPAY',
  '现金': 'MONEY',
  '银行卡': 'BANK_CARD',
  '其他': 'OTHER'
};

// 账户类型反向映射
const accountTypeReverseMap = {
  'WCHAT': '微信',
  'ALIPAY': '支付宝',
  'MONEY': '现金',
  'BANK_CARD': '银行卡',
  'OTHER': '其他'
};

// 联系人信息
const contactInfo = ref({
  id: '',
  name: '',
  img: ''
});

// 记录ID
const recordId = ref('');

// 修改表单数据，添加图片相关字段
const formData = reactive({
  images: [], // 用于UI展示的图片数组
  imageUrls: '', // 用于保存的图片URL字符串
});

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 显示类型选择器
const showTypeSelector = () => {
  typeSelectorVisible.value = true;
};

// 导航到类型选择页面
const navigateToTypeSelector = () => {
  uni.navigateTo({
    url: `/pages/contact/account-type-selector?defaultType=${encodeURIComponent(type.value)}`,
    events: {
      typeSelected: (data) => {
        if (data && data.type) {
          type.value = data.type;
        }
      }
    },
    success: (res) => {
      // 向类型选择页面传递当前已选类型
      if (res.eventChannel) {
        try {
          res.eventChannel.emit('getCurrentType', { currentType: type.value });
        } catch (e) {
          console.error('传递类型数据失败:', e);
        }
      }
    }
  });
};

// 获取人情收支记录详情
const getHumanTransactionDetail = async (id) => {
  try {
    uni.showLoading({
      title: '加载中...'
    });
    
    const res = await TransactionApi.queryHumanTransactionDetail({
      id: id
    });
    
    uni.hideLoading();
    
    if (res.code === 0 && res.data) {
      const detail = res.data;
      
      // 填充表单数据
      accountType.value = detail.transactionType === 'IN' ? '收入' : '支出';
      amount.value = detail.giftAmount ? detail.giftAmount.toString() : '';
      type.value = detail.eventTypeName || '';
      typeId.value = detail.eventTypeId;
      account.value = detail.accountType ? accountTypeReverseMap[detail.accountType] || '微信' : '微信';
      date.value = detail.eventDate || '';
      remark.value = detail.remark || '';
      eventName.value = detail.eventName || '';
      giftItem.value = detail.giftItem || '';
      
      // 处理图片URLs
      if (detail.imageUrls) {
        formData.imageUrls = detail.imageUrls;
        formData.images = detail.imageUrls.split(',');
      }
      
      // 更新联系人信息
      contactInfo.value = {
        id: detail.contactId || '',
        name: detail.contactName || '',
        img: ''
      };
    } else {
      uni.showToast({
        title: res.msg || '获取记录详情失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('获取人情收支记录详情失败:', error);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  }
};

// 添加页面显示事件监听
onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const { id, contactId, mode } = currentPage.options;
  
  console.log('页面参数:', { id, contactId, mode });
  
  isEdit.value = mode === 'edit';
  
  // 设置默认日期为今天
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  date.value = `${year}-${month}-${day}`;
  
  // 获取联系人信息
  if (contactId) {
    contactInfo.value.id = contactId;
  }
  
  if (isEdit.value && id) {
    // 编辑模式：获取现有记账数据
    recordId.value = id;
    getHumanTransactionDetail(id);
  }
  
  // 添加页面显示事件监听
  uni.$on('updateAccountType', (data) => {
    if (data && data.type) {
      if (typeof data.type === 'object') {
        type.value = data.type.name;
        typeId.value = data.type.id;
      } else {
        type.value = data.type;
      }
    }
  });
  
  // 从本地存储获取选择的类型
  const selectedType = uni.getStorageSync('selectedAccountType');
  if (selectedType && !type.value) {
    if (typeof selectedType === 'object') {
      type.value = selectedType.name;
      typeId.value = selectedType.id;
    } else {
      type.value = selectedType;
    }
    // 清除存储，避免影响下次选择
    uni.removeStorageSync('selectedAccountType');
  }
});

// 显示账户选择器
const showAccountSelector = () => {
  accountSelectorVisible.value = true;
};

// 类型选择回调
const onTypeSelected = (selectedType) => {
  type.value = selectedType;
};

// 账户选择回调
const onAccountSelected = (selectedAccount) => {
  account.value = selectedAccount;
};

// 显示日期选择器
const showDatePicker = () => {
  datePickerVisible.value = true;
};

// 日期选择回调
const onDateSelected = (result) => {
  if (result && result.date) {
    date.value = result.date;
  }
};

// 扫描发票
const scanInvoice = async () => {
  uni.chooseImage({
    count: 9,
    success: async (res) => {
      // 上传选中的图片
      for (const tempFilePath of res.tempFilePaths) {
        const result = await FileApi.uploadFile(tempFilePath);
        if (result && result.data) {
          formData.images.push(result.data);
        }
      }
      // 更新imageUrls
      formData.imageUrls = formData.images.join(',');
    }
  });
};

// 添加预览图片方法
const previewImage = (index) => {
  uni.previewImage({
    urls: formData.images,
    current: formData.images[index]
  });
};

// 添加删除图片方法
const deleteImage = (index) => {
  formData.images.splice(index, 1);
  formData.imageUrls = formData.images.join(',');
};

// 保存记账
const saveAccounting = async () => {
  // 验证数据
  if (!amount.value) {
    uni.showToast({
      title: '请输入金额',
      icon: 'none'
    });
    return;
  }
  
  if (!type.value) {
    uni.showToast({
      title: '请选择类型',
      icon: 'none'
    });
    return;
  }
  
  if (!date.value) {
    uni.showToast({
      title: '请选择日期',
      icon: 'none'
    });
    return;
  }
  
  // 获取联系人ID
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const contactId = currentPage.options.contactId || contactInfo.value.id;
  
  if (!contactId) {
    uni.showToast({
      title: '请选择联系人',
      icon: 'none'
    });
    return;
  }
  
  try {
    uni.showLoading({
      title: isEdit.value ? '更新中...' : '保存中...'
    });
    
    // 准备请求参数
    const params = {
      id: isEdit.value ? recordId.value : null,
      eventName: eventName.value || type.value,
      eventDate: date.value,
      transactionType: accountType.value === '收入' ? 'IN' : 'OUT',
      eventTypeId: typeId.value,
      contactId: contactId,
      giftAmount: parseFloat(amount.value),
      giftItem: giftItem.value,
      remark: remark.value,
      imageUrls: formData.imageUrls,
      accountType: accountTypeMap[account.value] || 'OTHER'
    };
    
    const res = await TransactionApi.addOrUpdateHumanTransaction(params);
    
    uni.hideLoading();
    
    if (res.code === 0) {
      uni.showToast({
        title: isEdit.value ? '记账已更新' : '记账已添加',
        icon: 'success'
      });
      
      // 移除通过事件通知上一页刷新的方式
      // const eventChannel = uni.getOpenerEventChannel();
      // eventChannel.emit('accountingUpdated', {});
      
      // 直接返回上一页，由上一页的onShow方法负责刷新数据
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      uni.showToast({
        title: res.msg || '操作失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('保存人情收支记录失败:', error);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  }
};
</script>

<style lang="scss" scoped>
.accounting-edit-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 10;
}

.left {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
}

.right {
  padding: 0 20rpx;
}

.save-btn {
  color: #007AFF;
  font-size: 32rpx;
}

.form-container {
  padding: 20rpx 0;
}

.tabs {
  display: flex;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.tab-item {
  flex: 1;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  color: #666;
  position: relative;
}

.tab-item.active {
  color: #007AFF;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 48rpx;
  height: 4rpx;
  background: #007AFF;
  border-radius: 2rpx;
}

.amount-input {
  display: flex;
  align-items: center;
  padding: 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.amount-field {
  flex: 1;
  height: 80rpx;
  font-size: 40rpx;
  font-weight: 500;
  color: #333;
}

.camera-icon {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  background-color: #fff;
  margin-bottom: 2rpx;
  position: relative;
}

.item-label {
  width: 200rpx;
  font-size: 32rpx;
  color: #333;
}

.item-value {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.type-value, .account-value, .date-value {
  font-size: 32rpx;
  color: #666;
  margin-right: 10rpx;
}

.remark-item {
  height: 200rpx;
  align-items: flex-start;
}

.remark-textarea {
  width: 100%;
  height: 160rpx;
  font-size: 32rpx;
  color: #333;
  padding: 0;
}

// 日期选择器样式
.date-picker-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}

.date-picker-wrapper {
  width: 100%;
  background-color: #fff;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  overflow: hidden;
}

.date-picker-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.date-picker-cancel {
  color: #333;
  font-size: 32rpx;
}

.date-picker-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.date-picker-confirm {
  color: #007AFF;
  font-size: 32rpx;
}

.date-picker-content {
  padding: 20rpx 0;
  height: 480rpx;
}

.date-picker-view {
  width: 100%;
  height: 100%;
}

.picker-item {
  line-height: 80rpx;
  text-align: center;
  font-size: 32rpx;
  color: #333;
}
.input-field {
  width: 100%;
  height: 60rpx;
  font-size: 32rpx;
  color: #666;
  text-align: right;
}

// 添加图片列表样式
.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  padding: 20rpx 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.image-item {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  border-radius: 8rpx;
  overflow: hidden;
  
  image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .delete-btn {
    position: absolute;
    top: 10rpx;
    right: 10rpx;
    width: 40rpx;
    height: 40rpx;
    background: rgba(0, 0, 0, 0.5);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .delete-icon {
      color: #fff;
      font-size: 32rpx;
      line-height: 1;
    }
  }
}

.bottom-save-button {
  position: fixed;
  left: 30rpx;
  right: 30rpx;
  bottom: 20rpx;
  height: 90rpx;
  background: linear-gradient(to right, #007AFF, #1E90FF);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 32rpx;
  font-weight: 500;
  z-index: 99;
  border-radius: 45rpx;
  box-shadow: 0 6rpx 20rpx rgba(0, 122, 255, 0.3);
  
  // 添加安全区域适配
  margin-bottom: constant(safe-area-inset-bottom);
  margin-bottom: env(safe-area-inset-bottom);
  
  // 添加点击效果
  &:active {
    transform: scale(0.98);
    box-shadow: 0 3rpx 10rpx rgba(0, 122, 255, 0.2);
  }
  
  text {
    color: #fff;
  }
}
</style>